import React, { useEffect, useState } from 'react';
import { wrap } from "popmotion"
import { useInView, animated } from '@react-spring/web'
import styles from "./CustomQy.module.scss";
import { AnimatePresence, m } from 'framer-motion';
import coumt1 from "@/assets/images/common/custom1.jpg"
import coumt2 from "@/assets/images/common/custom2.jpg"
const CustomQy = () => {

  const images = [coumt1, coumt2]

  const [ref, inView] = useInView({ once: true })

  const variants = {
    enter: (direction: number) => {
      return {
        x: direction > 0 ? 100 : -100,
        opacity: 0
      };
    },
    center: {
      zIndex: 1,
      x: 0,
      opacity: 1
    },
    exit: (direction: number) => {
      return {
        zIndex: 0,
        x: direction < 0 ? 100 : -100,
        opacity: 0
      };
    }
  };


  const [[page, direction], setPage] = useState([0, 0]);

  const imageIndex = wrap(0, images.length, page);

  useEffect(() => {

    //Implementing the setInterval method 
    const interval = setInterval(() => {
      paginate(1)
    }, 3000);

    //Clearing the interval 
    return () => clearInterval(interval);
  }, [page]);

  const paginate = (newDirection: number) => {
    setPage([page + newDirection, newDirection]);
  };

  const swipeConfidenceThreshold = 10000;
  const swipePower = (offset: number, velocity: number) => {
    return Math.abs(offset) * velocity;
  };

  return (
    <div className="w-1200px mx-auto h-full relative">
      <div className={styles['container']}>
        <AnimatePresence initial={true} custom={direction}>
          <m.img
            className={styles['img']}
            key={page}
            src={images[imageIndex]}
            custom={direction}
            variants={variants}
            initial="enter"
            animate="center"
            exit="exit"
            transition={{
              x: { type: "spring", stiffness: 500, damping: 20 },
              opacity: { duration: 0.2 }
            }}
            drag="x"
            dragConstraints={{ left: 0, right: 0 }}
            dragElastic={1}
            onDragEnd={(e: any, { offset, velocity }: any) => {
              const swipe = swipePower(offset.x, velocity.x);

              if (swipe < -swipeConfidenceThreshold) {
                paginate(1);
              } else if (swipe > swipeConfidenceThreshold) {
                paginate(-1);
              }
            }}
          />
        </AnimatePresence>
        <div className={styles['next']} onClick={() => paginate(1)}>
          {"‣"}
        </div>
        <div className={styles['prev']} onClick={() => paginate(-1)}>
          {"‣"}
        </div>
      </div>
    </div>

  )
}

export default CustomQy